// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: jhkim


#pragma once

#include "coin2/exchange/base/symbology/product_info.h"


namespace coin2::strategy::util {

inline double GetQtyFromQuote(
    const coin2::exchange::base::symbology::IProductHolder& pholder,
    double price,
    double quote) {
  const auto& pi = pholder.product_info();
  double contract_value = 1.0;
  if (pi.contract_value() > 0) {
    contract_value = pi.contract_value();
  }
  if (pi.is_inverse()) {
    return quote / contract_value;
  } else {
    return quote / price / contract_value;
  }
}


// This will prevent LUNA loss, when price goes to 0 too fast
// in this way it won't perform too much of SCALE TRADING
// but you need to provide price_24h_ago
// quote=1, price_24h_ago=1, price=1 -> qty = 1
// quote=1, price_24h_ago=1, price=0.5 -> qty = 2
// quote=1, price_24h_ago=1, price=0.25 -> qty = 2 (capped by price_24h_ago)
inline double GetQtyFromQuoteSafe(
    const coin2::exchange::base::symbology::IProductHolder& pholder,
    double price,
    double price_24h_ago,
    double quote) {
  double qty1 = GetQtyFromQuote(pholder, price, quote);
  double qty2 = 2 * GetQtyFromQuote(pholder, price_24h_ago, quote);
  if (quote < 0) {
    return std::max(qty1, qty2);
  } else {
    return std::min(qty1, qty2);
  }
}

}  // namespace coin2::strategy::util
